<template>
	<custom-layout custom-class="custom-layout">
		<!-- 表单 -->
		<wd-form ref="formRef" :model="formData">
			<wd-cell-group border>
				<wd-input v-model="formData.nickname" prop="nickname" label="用户昵称" placeholder="请输入用户昵称" clearable
					:rules="[{required:true,message:'请输入用户昵称'}]" />
				<wd-cell title="头像" prop="avatar" :rules="[{required:true,message:'请上传头像'}]">
					<wd-img v-if="formData.avatar" :width="60" :height="60" :src="formData.avatar" mode="aspectFill" />
					<wd-button size="small" open-type="chooseAvatar" @chooseavatar="handleGetAvatar">获取头像</wd-button>
				</wd-cell>
				<wd-cell title="手机号" prop="mobile" :rules="[{required:true,message:'请获取手机号'}]">
					{{formData.mobile}}
					<wd-button v-if="!formData.mobile" size="small" open-type="getPhoneNumber"
						@getphonenumber="handleGetPhoneNumber">获取手机号</wd-button>
				</wd-cell>
				<wd-input v-model="formData.wxCode" prop="wxCode" label="微信号" placeholder="请输入微信号" clearable />
				<wd-picker v-model="formData.sex" prop="sex" label="性别" :columns="dictionaryStore.get('system_user_sex')"
					placeholder="请选择性别" clearable :rules="[{required:true,message:'请选择性别'}]" />
				<wd-calendar v-model="formData.birthday" prop="birthday" label="出生日期" placeholder="请选择出生日期" />
				<wd-input v-if="!formData.proId" v-model="formData.invitationCode" prop="invitationCode" label="邀请码"
					placeholder="请输入邀请码" clearable />
			</wd-cell-group>
		</wd-form>
		<!-- 登录 -->
		<wd-button block size="large" custom-class="submit-button" @click="handleSubmit">登录</wd-button>
	</custom-layout>
</template>

<script setup>
	import {
		reactive,
		ref,
		watch
	} from 'vue';
	import {
		useDictionaryStore,
		useUserStore
	} from '@/store/index.js'
	import city from '@/utils/city.js'
	import {
		createClue
	} from '@/api/clue/create.js'
	import {
		getPhoneNumber,
		saveUserInfo
	} from '@/api/user/info.js'
	import config from '@/config/index.js'
	import {
		onShow
	} from '@dcloudio/uni-app'

	// 字典仓库
	const dictionaryStore = useDictionaryStore()
	// 用户仓库
	const userStore = useUserStore()
	// 表单ref
	const formRef = ref()
	// 表单数据
	const formData = reactive({
		birthday: null
	})
	watch(() => userStore.userInfo, () => {
		const keys = Object.keys(userStore.userInfo)
		if (keys.length > 1) {
			keys.forEach(key => {
				formData[key] = userStore.userInfo[key]
			})
		}
	}, {
		immediate: true
	})
	
	// 处理登录
	const handleSubmit = async () => {
		// 表单验证
		const validateResult = await formRef.value.validate();
		if (!validateResult.valid) return;
		try {
			

			// 显示加载提示
			uni.showLoading({
				mask: true
			});

			// 先执行 userStore.wxLogin() 异步操作
			await userStore.wxLogin()

			const params = {
				...formData,
				id: userStore.userId,
			}
	
			// 执行请求后端的接口
			await saveUserInfo(params)

			// 刷新缓存
			await userStore.getUserInfo()
		

		} catch (error) {
			// 显示错误提示
			setTimeout(() => {
				uni.showToast({
					title: error,
					icon: 'error'
				})
			})
		} finally {
			// 隐藏加载提示
			uni.hideLoading();
			uni.switchTab({
				url:'/pages/index/index'
			})
		
		}
	}
	// 处理获取手机号
	const handleGetPhoneNumber = ({
		code
	}) => {
		if (!code) {
			uni.showToast({
				title: '获取手机号失败',
				icon: 'error'
			})
			return
		}
		uni.showLoading({
			mask: true
		})
		getPhoneNumber({
			code
		}).then(data => {
			formData.mobile = data.phone_info.phoneNumber
		}).catch((error) => {
			setTimeout(() => {
				uni.showToast({
					title: error,
					icon: 'error'
				})
			})
		}).finally(() => {
			uni.hideLoading()
		})
	}
	// 处理获取头像
	const handleGetAvatar = ({
		avatarUrl
	}) => {
		uni.uploadFile({
			url: `${config.serverUrl[process.env.NODE_ENV]}/infra/file/upload`,
			filePath: avatarUrl,
			name: 'file',
			header: {
				'tenant-id': '1'
			},
			success: (res) => {
				const data = JSON.parse(res.data)
				if (data.code === 0) {
					formData.avatar = data.data
				} else {
					uni.showToast({
						title: data.msg,
						icon: 'error'
					})
				}
			},
			fail: () => {
				uni.showToast({
					title: '上传失败',
					icon: 'error'
				})
			}
		})
	}
	onShow(() => {

		// 隐藏home返回标识
        // if (uni.hideHomeButton) {
        //    console.log('uni.hideHomeButton');
        //    wx.hideHomeButton();
        // }
        
	})
</script>

<style lang="scss" scoped>
	// 自定义布局
	:deep(.custom-layout) {
		background: #F8F8F8;
	}

	// 上传样式
	:deep(.upload-style) {
		width: 120rpx !important;
		height: 120rpx !important;
	}

	// 登录按钮
	:deep(.submit-button) {
		margin: 32rpx;
	}
</style>